<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { createAdminUserApi, updateAdminUserApi } from '@/api/user'
import { AdminUserItem, AdminUserCreateParam, AdminUserUpdateParam } from '@/api/user/types'
import { useValidator } from '@/hooks/web/useValidator'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<AdminUserItem>,
    default: () => undefined
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const rules = reactive({
  userName: [required()],
  password: [required()],
  roleId: [required()],
  status: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const createUser = async (data: any) => {
  const param: AdminUserCreateParam = {
    userName: data.userName,
    password: data.password,
    roleId: data.roleId,
    status: data.status
  }
  const res = await createAdminUserApi(param)
  return res.code === 200
}

const updateUser = async (data: any) => {
  const param: AdminUserUpdateParam = {
    id: data.id,
    roleId: data.roleId,
    status: data.status
  }
  const res = await updateAdminUserApi(param)
  return res.code === 200
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (formData.id) {
      // 修改
      return updateUser(formData)
    } else {
      // 新增
      return createUser(formData)
    }
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
